package com.xyhuo.leetcode.november;

/**
 * 最大正方形
 * https://leetcode.cn/problems/maximal-square
 *
 * @time 2023/11/24
 */
public class MaximalSquare {

    public int maximalSquare(char[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m][n];
        int maxEdgeLength = 0;
        for (int i = 0; i < n; i++) {
            dp[0][i] = matrix[0][i] == '1' ? 1 : 0;
            if (dp[0][i] > maxEdgeLength) {
                maxEdgeLength = dp[0][i];
            }
        }
        for (int i = 0; i < m; i++) {
            dp[i][0] = matrix[i][0] == '1' ? 1 : 0;
            if (dp[i][0] > maxEdgeLength) {
                maxEdgeLength = dp[i][0];
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == '1') {
                    if (dp[i - 1][j - 1] != 0) {
                        int edgeLength = dp[i - 1][j - 1];
                        int curEdgeLength = 1;
                        for (int k = 1; k <= edgeLength; k++) {
                            if (j - k >= 0 && i - k >= 0 && matrix[i][j - k] == '1' && matrix[i - k][j] == '1') {
                                curEdgeLength++;
                            } else {
                                break;
                            }
                        }
                        dp[i][j] = curEdgeLength;
                    } else {
                        dp[i][j] = 1;
                    }
                    if (dp[i][j] > maxEdgeLength) {
                        maxEdgeLength = dp[i][j];
                    }
                }
            }
        }
        return maxEdgeLength * maxEdgeLength;
    }
}
